package com.graduation.check.controller;

import com.graduation.check.dto.*;
import com.graduation.check.entity.User;
import com.graduation.check.service.TeacherStudentService;
import com.graduation.check.utils.ApiResponse;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/teacher/students")  // context-path=/api已在application.properties配置
@CrossOrigin(origins = "*")
public class TeacherStudentController {
    
    @Autowired
    private TeacherStudentService teacherStudentService;
    
    /**
     * 获取学生列表
     */
    @GetMapping
    public ApiResponse<StudentListResponse> getStudentList(StudentListRequest request) {
        try {
            StudentListResponse response = teacherStudentService.getStudentList(request);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取学生列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 按班级分组获取学生
     */
    @GetMapping("/by-class")
    public ApiResponse<Map<String, Object>> getStudentsByClass(
            @RequestParam(required = false) String major) {
        try {
            Map<String, Object> result = teacherStudentService.getStudentsByClass(major);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取学生分组失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加学生
     */
    @PostMapping
    public ApiResponse<User> addStudent(@Valid @RequestBody AddStudentRequest request) {
        try {
            User user = teacherStudentService.addStudent(request);
            return ApiResponse.success("学生添加成功", user);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 更新学生信息
     */
    @PutMapping("/{studentId}")
    public ApiResponse<User> updateStudent(
            @PathVariable Long studentId,
            @RequestBody UpdateStudentRequest request) {
        try {
            User user = teacherStudentService.updateStudent(studentId, request);
            return ApiResponse.success("学生信息更新成功", user);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 删除学生
     */
    @DeleteMapping("/{studentId}")
    public ApiResponse<Void> deleteStudent(@PathVariable Long studentId) {
        try {
            teacherStudentService.deleteStudent(studentId);
            return ApiResponse.success("学生删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 批量删除学生
     */
    @DeleteMapping("/batch")
    public ApiResponse<Map<String, Object>> batchDeleteStudents(@RequestBody List<Long> studentIds) {
        try {
            Map<String, Object> result = teacherStudentService.batchDeleteStudents(studentIds);
            return ApiResponse.success("批量删除完成", result);
        } catch (Exception e) {
            return ApiResponse.error(500, "批量删除失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量导入学生
     */
    @PostMapping("/batch-import")
    public ApiResponse<Map<String, Object>> batchImportStudents(
            @RequestParam("file") MultipartFile file) {
        try {
            Map<String, Object> result = teacherStudentService.batchImportStudents(file);
            return ApiResponse.success("导入完成", result);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 导出学生列表
     */
    @GetMapping("/export")
    public void exportStudentList(StudentListRequest request, HttpServletResponse response) {
        try {
            // 获取学生数据
            StudentListResponse studentList = teacherStudentService.getStudentList(request);
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=students.xlsx");
            
            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("学生列表");
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"学号", "姓名", "邮箱", "专业", "班级", "状态", "提交次数", "注册时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            
            // 填充数据
            List<StudentListItem> students = studentList.getRecords();
            for (int i = 0; i < students.size(); i++) {
                StudentListItem student = students.get(i);
                Row row = sheet.createRow(i + 1);
                
                row.createCell(0).setCellValue(student.getAccount());
                row.createCell(1).setCellValue(student.getName());
                row.createCell(2).setCellValue(student.getEmail());
                row.createCell(3).setCellValue(student.getMajor());
                row.createCell(4).setCellValue(student.getClassName());
                row.createCell(5).setCellValue(student.getStatus() == 1 ? "正常" : "禁用");
                row.createCell(6).setCellValue(student.getSubmissionCount() != null ? student.getSubmissionCount() : 0);
                row.createCell(7).setCellValue(student.getCreateTime() != null ? student.getCreateTime().toString() : "");
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 写入响应
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败: " + e.getMessage());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}